//
//  CaptureViewController.m
//  SBVideoCaptureDemo
//
//  Created by Pandara on 14-8-12.
//  Copyright (c) 2014年 Pandara. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "CaptureViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <MediaPlayer/MediaPlayer.h>
#import "ProgressBar.h"
#import "SBCaptureToolKit.h"
#import "SBVideoRecorder.h"
#import "DeleteButton.h"
//#import "PlayViewController.h"
//#import "MBProgressHUD.h"
#import "CircularProgressView.h"
#import "SVProgressHUD.h"

#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import "Common.h"

#define TIMER_INTERVAL 0.05f

#define TAG_ALERTVIEW_CLOSE_CONTROLLER 10086

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT   [[UIScreen mainScreen] bounds].size.height

@interface CaptureViewController ()

@property (strong, nonatomic) UIView *maskView;

@property (strong, nonatomic) SBVideoRecorder *recorder;

@property (strong, nonatomic) ProgressBar *progressBar;

@property (strong, nonatomic) DeleteButton *deleteButton;
@property (strong, nonatomic) UIButton *okButton;

@property (strong, nonatomic) UIButton *closeButton;
@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIButton *settingButton;
@property (strong, nonatomic) UIButton *recordButton;
@property (strong, nonatomic) UIButton *flashButton;
@property (strong, nonatomic) CircularProgressView *circularProgressView;
@property (strong, nonatomic) NSString *imagePath;
@property (strong, nonatomic) UIImageView *rhythmImage;


//@property (strong, nonatomic) MBProgressHUD *hud;

@property (assign, nonatomic) BOOL initalized;
@property (assign, nonatomic) BOOL isProcessingData;

@property (strong, nonatomic) UIView *preview;
@property (strong, nonatomic) UIImageView *focusRectView;
@property (strong, nonatomic) NSTimer *imageTime;
@property (assign, nonatomic) BOOL isON;
@property (strong, nonatomic) UISlider *mySlider;
@property (strong, nonatomic) AVAudioPlayer *avAudioPlayer;

@property (strong, nonatomic) UIImage *avAudioImage;


@end

@implementation CaptureViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNeedsStatusBarAppearanceUpdate];
//    self.view.backgroundColor = color(16, 16, 16, 1);
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"APPBG"]];
    
    UIImageView *imageBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    imageBG.image = [UIImage imageNamed:@"APPBG"];
    [self.view addSubview:imageBG];
    
    self.maskView = [self getMaskView];
    [self.view addSubview:_maskView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //监听耳机事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputDeviceChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    
    if (_initalized) {
        return;
    }
    
    [self initPreview];
    [self initRecorder];
//    [self initAVAudio];
    [SBCaptureToolKit createVideoFolderIfNotExist];
//    [self initProgressBar];
    [self initRecordButton];
//    [self initDeleteButton];
    [self initOKButton];
    [self initTopLayout];
    
    [self hideMaskView];
    
    self.initalized = YES;
}

- (void)initPreview
{
    self.preview = [[UIView alloc] initWithFrame:CGRectMake(0, 127/2, DEVICE_SIZE.width, DEVICE_SIZE.width)];
    _preview.clipsToBounds = YES;
    [self.view insertSubview:_preview belowSubview:_maskView];
    
//    self.mySlider = [[UISlider alloc] initWithFrame:CGRectMake(5, SCREEN_HEIGHT - 60, 568/2, 48/2)];
////    self.mySlider.backgroundColor = [UIColor redColor];
//    [self.mySlider addTarget:self action:@selector(speedSliderAction:) forControlEvents:UIControlEventValueChanged];
//    self.mySlider.backgroundColor = [UIColor clearColor];
//    UIImage *stetchTrack = [[UIImage imageNamed:@"SF_Bar_ON"]
//                            stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
//    [self.mySlider setThumbImage: [UIImage imageNamed:@"Slider_H"] forState:UIControlStateNormal];
//    [self.mySlider setMinimumTrackImage:stetchTrack forState:UIControlStateNormal];
//    [self.mySlider setMaximumTrackImage:stetchTrack forState:UIControlStateNormal];
//    [self.view insertSubview:self.mySlider belowSubview:_maskView];
    
}

- (void)initAVAudio{
    NSString *string = [[NSBundle mainBundle] pathForResource:@"5473" ofType:@"mp3"];
    //把音频文件转换成url格式
     NSURL *url = [NSURL fileURLWithPath:string];
    //初始化音频类 并且添加播放文件
    _avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    //设置代理
    [_avAudioPlayer setDelegate:(id<AVAudioPlayerDelegate>)self];
//    _avAudioPlayer.numberOfLoops = -1;
    [_avAudioPlayer prepareToPlay];
//    DLog(@"_avAudioPlayer=====%f",_avAudioPlayer.duration);
}

- (void)initRecorder
{
    self.recorder = [[SBVideoRecorder alloc] init];
    _recorder.delegate = self;
    _recorder.preViewLayer.frame = CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.width);
    [self.preview.layer addSublayer:_recorder.preViewLayer];
}

- (void)initProgressBar
{
    self.progressBar = [ProgressBar getInstance];
    [SBCaptureToolKit setView:_progressBar toOriginY:DEVICE_SIZE.width];
    [self.view insertSubview:_progressBar belowSubview:_maskView];
    [_progressBar startShining];
}

- (void)initDeleteButton
{
    if (_isProcessingData) {
        return;
    }
    
    self.deleteButton = [DeleteButton getInstance];
    [_deleteButton setButtonStyle:DeleteButtonStyleDisable];
    [SBCaptureToolKit setView:_deleteButton toOrigin:CGPointMake(15, self.view.frame.size.height - _deleteButton.frame.size.height - 10)];
    [_deleteButton addTarget:self action:@selector(pressDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    
    CGPoint center = _deleteButton.center;
    center.y = _recordButton.center.y;
    _deleteButton.center = center;
    
    [self.view insertSubview:_deleteButton belowSubview:_maskView];
    
}

- (void)initRecordButton
{
    CGFloat buttonW = 93.f;
    
    _circularProgressView = [[CircularProgressView alloc] initWithFrame:CGRectMake((DEVICE_SIZE.width - buttonW) / 2.0 - 1, SCREEN_WIDTH + 127/2 + 48 - 1, buttonW + 2, buttonW + 2)];
    self.circularProgressView.backColor = [UIColor clearColor];
    self.circularProgressView.progressColor = [UIColor colorWithRed:255.f/255.f green:234.f/255.f blue:77.f/255.f alpha:1.000];
    self.circularProgressView.lineWidth = 4;
    
    //set CircularProgressView delegate
    [self.circularProgressView setDelegate:(id<CircularProgressViewDelegate>)self];
    
    self.circularProgressView.backgroundColor = [UIColor clearColor];
    [self.view insertSubview:_circularProgressView belowSubview:_maskView];
    
//    self.recordButton = [[UIButton alloc] initWithFrame:CGRectMake((DEVICE_SIZE.width - 93) / 2.0, SCREEN_WIDTH + 127/2 + 48, 93, 93)];
//    [_recordButton setImage:[UIImage imageNamed:@"Record_OFF"] forState:UIControlStateNormal];
//    [_recordButton setImage:[UIImage imageNamed:@"Record_ON"] forState:UIControlStateSelected];
//    [_recordButton setImage:[UIImage imageNamed:@"Record_ON"] forState:UIControlStateHighlighted];
//    _recordButton.userInteractionEnabled = NO;
//    [self.view insertSubview:_recordButton belowSubview:_maskView];
    
    self.recordButton = [[UIButton alloc] initWithFrame:CGRectMake((DEVICE_SIZE.width - 93) / 2.0, SCREEN_WIDTH + 127/2 + 48, 93, 93)];
    [_recordButton setImage:[UIImage imageNamed:@"Record_OFF"] forState:UIControlStateNormal];
    [_recordButton setImage:[UIImage imageNamed:@"Record_ON"] forState:UIControlStateSelected];
    [_recordButton setImage:[UIImage imageNamed:@"Record_ON"] forState:UIControlStateHighlighted];
//    _recordButton.userInteractionEnabled = NO;
    [self.recordButton addTarget:self action:@selector(recordButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_recordButton belowSubview:_maskView];
    
    
//    _rhythmImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 46/2 - 136/2, SCREEN_WIDTH + 127/2 + 48 + 5, 136/2, 136/2)];
//    _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
//    [self.view insertSubview:_rhythmImage belowSubview:_maskView];
    
//    UIButton *tempBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 46/2 - 134/2, _rhythmImage.frame.origin.y + _rhythmImage.frame.size.height + 10, 134/2, 52/2)];
//    [tempBtn setImage:[UIImage imageNamed:@"dida.png"] forState:UIControlStateNormal];
//    [self.view insertSubview:tempBtn belowSubview:_maskView];

    
}

- (void)recordButtonClick:(id)sender{
    if (!_recordButton.selected) {
        _avAudioImage=[self getVideoShotImage];
        NSLog(@"%@",_avAudioImage);
        NSLog(@"1");
        [self.circularProgressView play];
        self.circularProgressView.playOrPauseButtonIsPlaying = YES;
        NSString *filePath = [SBCaptureToolKit getVideoSaveFilePathStringWithVideoTag:_videoTag];
        if ([self isHeadphone] == YES) {
            _imageTime = [NSTimer scheduledTimerWithTimeInterval:_avAudioPlayer.duration + [_mySlider value] target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        }
        [_recorder startRecordingToOutputFileURL:[NSURL fileURLWithPath:filePath]];
        _recordButton.selected = YES;
    }else{
        NSLog(@"2");
        _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
        [_imageTime invalidate];
        _recordButton.selected = NO;
        [_recorder stopCurrentVideoRecording];
        
        [_circularProgressView pause];
    }
}

#pragma mark 判断耳机是否插入 yes表示插入  no表示没有插入
- (BOOL)isHeadphone
{
    UInt32 propertySize = sizeof(CFStringRef);
    CFStringRef state = nil;
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute
                            ,&propertySize,&state);
    //return @"Headphone" or @"Speaker" and so on.
    //根据状态判断是否为耳机状态
    if ([(__bridge NSString *)state isEqualToString:@"Headphone"] ||[(__bridge NSString *)state isEqualToString:@"HeadsetInOut"])
    {
        return YES;
    }
    else {
        return NO;
    } 
}

#pragma mark 滴答声音的播放 开一个time
- (void)timerFired{
    if (!_isON) {
        _isON = YES;
        [_avAudioPlayer stop];
        _rhythmImage.image = [UIImage imageNamed:@"Preview_OFF"];
    }else{
        _isON = NO;
        [_avAudioPlayer play];
        _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
    }
}

- (void)speedSliderAction:(id)sender{
    DLog(@"value=========%.2f",[_mySlider value]);
    if ([self isHeadphone] == YES) {
        [_imageTime invalidate];
        _imageTime = [NSTimer scheduledTimerWithTimeInterval:_avAudioPlayer.duration + [_mySlider value] target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    }else{
        
    }
    
//    _avAudioPlayer.enableRate = YES;
//    [_avAudioPlayer play];
//    [_avAudioPlayer setRate:2];
}

#pragma mark 耳机监听
- (void)outputDeviceChanged:(NSNotification *)notification

{
    
    DLog(@"[AVAudioSession sharedInstance]=====%@",notification.userInfo);
    NSDictionary *interuptionDict = notification.userInfo;
    
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    
    switch (routeChangeReason) {
            
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:{
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            NSLog(@"Headphone/Line plugged in");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"耳机插入" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [_imageTime invalidate];
            _imageTime = [NSTimer scheduledTimerWithTimeInterval:_avAudioPlayer.duration + 0.2f target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        }
            break;
            
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:{
            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            NSLog(@"Headphone/Line was pulled. Stopping player....");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"耳机拔出" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [_avAudioPlayer stop];
            [_imageTime invalidate];
        }
            break;
            
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
    
    // do your jobs here
    
}

- (void)initOKButton
{
//    CGFloat okButtonW = 50;
    self.okButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 33/2 - 67/2, 45/2, 67/2, 67/2)];
    _okButton.enabled = NO;
    [_okButton setImage:[UIImage imageNamed:@"submitBtn"] forState:UIControlStateNormal];
    [_okButton addTarget:self action:@selector(pressOKButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view insertSubview:_okButton belowSubview:_maskView];
}

- (void)initTopLayout
{
    
//    UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 43/2, SCREEN_WIDTH, 67/2)];
//    titleLbl.text = @"单轨录制";
//    titleLbl.textColor = [UIColor colorWithRed:255.f/255.f green:234.f/255.f blue:77.f/255.f alpha:1.000];
//    titleLbl.textAlignment = NSTextAlignmentCenter;
//    [self.view insertSubview:titleLbl belowSubview:_maskView];
    
    UIImageView *cameraBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 127/2, SCREEN_WIDTH, SCREEN_WIDTH)];
    cameraBG.image = [UIImage imageNamed:@"CameraBG"];
    [self.view insertSubview:cameraBG belowSubview:_maskView];
    
    //关闭
    self.closeButton = [[UIButton alloc] initWithFrame:CGRectMake(36/2, 43/2, 67/2, 67/2)];
    [_closeButton setImage:[UIImage imageNamed:@"backBtn1"] forState:UIControlStateNormal];
//    [_closeButton setImage:[UIImage imageNamed:@"record_close_disable.png"] forState:UIControlStateDisabled];
//    [_closeButton setImage:[UIImage imageNamed:@"record_close_highlighted.png"] forState:UIControlStateSelected];
//    [_closeButton setImage:[UIImage imageNamed:@"record_close_highlighted.png"] forState:UIControlStateHighlighted];
    [_closeButton addTarget:self action:@selector(pressCloseButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_closeButton belowSubview:_maskView];
    
//    //前后摄像头转换
    self.switchButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - (67/2 + 10) * 2 - 10, 45/2, 67/2, 67/2)];
    [_switchButton setImage:[UIImage imageNamed:@"record_lensflip_normal.png"] forState:UIControlStateNormal];
    [_switchButton setImage:[UIImage imageNamed:@"record_lensflip_disable.png"] forState:UIControlStateDisabled];
    [_switchButton setImage:[UIImage imageNamed:@"record_lensflip_highlighted.png"] forState:UIControlStateSelected];
    [_switchButton setImage:[UIImage imageNamed:@"record_lensflip_highlighted.png"] forState:UIControlStateHighlighted];
    [_switchButton addTarget:self action:@selector(pressSwitchButton) forControlEvents:UIControlEventTouchUpInside];
    _switchButton.enabled = [_recorder isFrontCameraSupported];
    [self.view insertSubview:_switchButton belowSubview:_maskView];
    
    //setting
//    self.settingButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - (buttonW + 10), 5, buttonW, buttonW)];
//    [_settingButton setImage:[UIImage imageNamed:@"record_tool_normal.png"] forState:UIControlStateNormal];
//    [_settingButton setImage:[UIImage imageNamed:@"record_tool_disable.png"] forState:UIControlStateDisabled];
//    [_settingButton setImage:[UIImage imageNamed:@"record_tool_highlighted.png"] forState:UIControlStateSelected];
//    [_settingButton setImage:[UIImage imageNamed:@"record_tool_highlighted.png"] forState:UIControlStateHighlighted];
//    [self.view insertSubview:_settingButton belowSubview:_maskView];
    
    
//    self.flashButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - (buttonW + 10), 5, buttonW, buttonW)];
//    [_flashButton setImage:[UIImage imageNamed:@"record_flashlight_normal.png"] forState:UIControlStateNormal];
//    [_flashButton setImage:[UIImage imageNamed:@"record_flashlight_disable.png"] forState:UIControlStateDisabled];
//    [_flashButton setImage:[UIImage imageNamed:@"record_flashlight_highlighted.png"] forState:UIControlStateHighlighted];
//    [_flashButton setImage:[UIImage imageNamed:@"record_flashlight_highlighted.png"] forState:UIControlStateSelected];
//    _flashButton.enabled = _recorder.isTorchSupported;
//    [_flashButton addTarget:self action:@selector(pressFlashButton) forControlEvents:UIControlEventTouchUpInside];
//    [self.view insertSubview:_flashButton belowSubview:_maskView];
//    
//    //focus rect view
//    self.focusRectView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
//    _focusRectView.image = [UIImage imageNamed:@"touch_focus_not.png"];
//    _focusRectView.alpha = 0;
//    [self.preview addSubview:_focusRectView];
}

- (void)pressCloseButton
{
    if ([_recorder getVideoCount] > 0) {
        _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
        [_imageTime invalidate];
        _recordButton.selected = NO;
        [_recorder stopCurrentVideoRecording];
        [_circularProgressView pause];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您确定要放弃视频录制?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"放弃", nil];
        alertView.tag = TAG_ALERTVIEW_CLOSE_CONTROLLER;
        [alertView show];
    } else {
        [self dropTheVideo];
    }
}

- (void)pressSwitchButton
{
    _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
    [_imageTime invalidate];
    _recordButton.selected = NO;
    [_recorder stopCurrentVideoRecording];
    [_circularProgressView pause];
    
    _switchButton.selected = !_switchButton.selected;
    if (_switchButton.selected) {//换成前摄像头
        if (_flashButton.selected) {
            [_recorder openTorch:NO];
            _flashButton.selected = NO;
            _flashButton.enabled = NO;
        } else {
            _flashButton.enabled = NO;
        }
    } else {
        _flashButton.enabled = [_recorder isFrontCameraSupported];
    }
    
    [_recorder switchCamera];
}

- (void)pressFlashButton
{
    _flashButton.selected = !_flashButton.selected;
    [_recorder openTorch:_flashButton.selected];
}

- (void)pressDeleteButton
{
    if (_deleteButton.style == DeleteButtonStyleNormal) {//第一次按下删除按钮
        [_progressBar setLastProgressToStyle:ProgressBarProgressStyleDelete];
        [_deleteButton setButtonStyle:DeleteButtonStyleDelete];
    } else if (_deleteButton.style == DeleteButtonStyleDelete) {//第二次按下删除按钮
        [self deleteLastVideo];
        [_progressBar deleteLastProgress];
        
        if ([_recorder getVideoCount] > 0) {
            [_deleteButton setButtonStyle:DeleteButtonStyleNormal];
        } else {
            [_deleteButton setButtonStyle:DeleteButtonStyleDisable];
        }
    }
}

- (void)pressOKButton
{
    if (_isProcessingData) {
        return;
    }
    _rhythmImage.image = [UIImage imageNamed:@"Preview_ON"];
    [_imageTime invalidate];
    _recordButton.selected = NO;
    [_recorder stopCurrentVideoRecording];
    [_circularProgressView pause];
    
//    if (!self.hud) {
//        self.hud = [[MBProgressHUD alloc] initWithView:self.view];
//        _hud.labelText = @"努力处理中";
//    }
//    [_hud show:YES];
//    [self.view addSubview:_hud];
    
    [_recorder mergeVideoFiles];
    self.isProcessingData = YES;
}

//放弃本次视频，并且关闭页面
- (void)dropTheVideo
{
    [_recorder deleteAllVideo];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//删除最后一段视频
- (void)deleteLastVideo
{
    if ([_recorder getVideoCount] > 0) {
        [_recorder deleteLastVideo];
    }
}

- (void)hideMaskView
{
    [UIView animateWithDuration:0.5f animations:^{
        CGRect frame = self.maskView.frame;
        frame.origin.y = self.maskView.frame.size.height;
        self.maskView.frame = frame;
    }];
}

- (UIView *)getMaskView
{
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.height + DELTA_Y)];
    maskView.backgroundColor = color(30, 30, 30, 1);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.height)];
    label.font = [UIFont systemFontOfSize:50.0f];
    label.textColor = color(100, 100, 100, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"";
    label.backgroundColor = [UIColor clearColor];
    
    [maskView addSubview:label];
    
    return maskView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)showFocusRectAtPoint:(CGPoint)point
{
    _focusRectView.alpha = 1.0f;
    _focusRectView.center = point;
    _focusRectView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
    [UIView animateWithDuration:0.2f animations:^{
        _focusRectView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    } completion:^(BOOL finished) {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
        animation.values = @[@0.5f, @1.0f, @0.5f, @1.0f, @0.5f, @1.0f];
        animation.duration = 0.5f;
        [_focusRectView.layer addAnimation:animation forKey:@"opacity"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3f animations:^{
                _focusRectView.alpha = 0;
            }];
        });
    }];
//    _focusRectView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
//    _focusRectView.center = point;
//    [UIView animateWithDuration:0.3f animations:^{
//        _focusRectView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//        _focusRectView.alpha = 1.0f;
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:0.1f animations:^{
//            _focusRectView.alpha = 0.0f;
//        }];
//    }];
}


//- (void)startProgressTimer
//{
//    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
//    self.progressCounter = 0;
//}
//
//- (void)stopProgressTimer
//{
//    [_progressTimer invalidate];
//    self.progressTimer = nil;
//}
//
//- (void)onTimer:(NSTimer *)timer
//{
//    self.progressCounter++;
//    [_progressBar setLastProgressToWidth:self.progressCounter * TIMER_INTERVAL / MAX_VIDEO_DUR * DEVICE_SIZE.width];
//}

#pragma mark - SBVideoRecorderDelegate
- (void)videoRecorder:(SBVideoRecorder *)videoRecorder didStartRecordingToOutPutFileAtURL:(NSURL *)fileURL
{
    
    NSLog(@"正在录制视频: %@", fileURL);
    
    
    
    [self.progressBar addProgressView];
    [_progressBar stopShining];
    
    [_deleteButton setButtonStyle:DeleteButtonStyleNormal];
}

- (void)videoRecorder:(SBVideoRecorder *)videoRecorder didFinishRecordingToOutPutFileAtURL:(NSURL *)outputFileURL duration:(CGFloat)videoDuration totalDur:(CGFloat)totalDur error:(NSError *)error
{
    if (error) {
        NSLog(@"录制视频错误:%@", error);
    } else {
        NSLog(@"录制视频完成: %@", outputFileURL);
    }
    
    [_progressBar startShining];
    
    NSLog(@"MAX_VIDEO_DUR=====%f",MAX_VIDEO_DUR);
    if (totalDur >= MAX_VIDEO_DUR) {
        [self pressOKButton];
    }
}

- (void)videoRecorder:(SBVideoRecorder *)videoRecorder didRemoveVideoFileAtURL:(NSURL *)fileURL totalDur:(CGFloat)totalDur error:(NSError *)error
{
    if (error) {
        NSLog(@"删除视频错误: %@", error);
    } else {
        NSLog(@"删除了视频: %@", fileURL);
        NSLog(@"现在视频长度: %f", totalDur);
    }
    [_imageTime invalidate];
    [_avAudioPlayer stop];
    if ([_recorder getVideoCount] > 0) {
        [_deleteButton setStyle:DeleteButtonStyleNormal];
    } else {
        [_deleteButton setStyle:DeleteButtonStyleDisable];
    }
    
    _okButton.enabled = (totalDur >= MIN_VIDEO_DUR);
}

- (void)videoRecorder:(SBVideoRecorder *)videoRecorder didRecordingToOutPutFileAtURL:(NSURL *)outputFileURL duration:(CGFloat)videoDuration recordedVideosTotalDur:(CGFloat)totalDur
{
    [_progressBar setLastProgressToWidth:videoDuration / MAX_VIDEO_DUR * _progressBar.frame.size.width];
    
    _okButton.enabled = (videoDuration + totalDur >= MIN_VIDEO_DUR);
}

//视频处理完成
- (void)videoRecorder:(SBVideoRecorder *)videoRecorder didFinishMergingVideosToOutPutFileAtURL:(NSURL *)outputFileURL
{
    [SVProgressHUD showWithStatus:@"视频上传中..."];
//    [_hud hide:YES];
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.isProcessingData = NO;
    SBC.videoUrl = outputFileURL;
    
    NSLog(@"处理完成=====");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray *tempArr=[[NSMutableArray alloc]init];
        if (![_avAudioImage isEqual:[NSNull null]]) {
            [tempArr addObject:_avAudioImage];
        }
//       tempArr = [self getVideoImageWithVideoUrl:outputFileURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
//            [hud hide:YES];
            [self dismissViewControllerAnimated:YES completion:^{
//                [hud hide:YES];
                
                        if ([_videoDelegate respondsToSelector:@selector(videoBackDelegateWithUrl:videoImageArr:withImageFrmae:)]) {
                            [_videoDelegate videoBackDelegateWithUrl:outputFileURL videoImageArr:tempArr withImageFrmae:_imageFrame];
                        }
                
            }];
        });
    });
    
    
    
    
    
    
//    PlayViewController *playCon = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil withVideoFileURL:outputFileURL];
//    [self.navigationController pushViewController:playCon animated:YES];
}

- (NSArray *)getVideoImageWithVideoUrl:(NSURL *)videoUrl{
    
    NSMutableArray *videoImageArr = [NSMutableArray array];
    
    NSURL *fileURL = videoUrl;
    
    AVURLAsset* movie = [AVURLAsset URLAssetWithURL:fileURL options:nil];
    NSArray* tracks = [movie tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *track = [tracks firstObject];
    NSError* error = nil;
    AVAssetReader* areader = [[AVAssetReader alloc] initWithAsset:movie error:&error];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithInt:kCVPixelFormatType_32ARGB ], kCVPixelBufferPixelFormatTypeKey,
                             nil];
    AVAssetReaderTrackOutput* rout = [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:options];
    [areader addOutput:rout];
    [areader startReading];
    
    NSString *tempPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/Pictures-%ld",(long)_videoTag]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:tempPath error:nil];
    
    while (areader.status == AVAssetReaderStatusReading) {
        CMSampleBufferRef sbuff = [rout copyNextSampleBuffer];
        if (sbuff) {
            // progressing ...
            //            UIImageWriteToSavedPhotosAlbum([self imageFromSampleBuffer:sbuff], nil, nil, nil);
            UIImage *image = [UIImage imageWithData:UIImageJPEGRepresentation([self imageFromSampleBuffer:sbuff], 0.5)];
            if (videoImageArr.count > 0) {
                
            }else{
                [videoImageArr addObject:image];
            }
//            [videoImageArr addObject:image];
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            formatter.dateFormat = @"yyyyMMddHHmmss";
//            NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
//            NSLog(@"_pictureBasePath=====%@",tempPath);
            BOOL isDirectory = YES;
            BOOL folderExists = [[NSFileManager defaultManager] fileExistsAtPath:tempPath isDirectory:&isDirectory] && isDirectory;
            if (!folderExists){
                NSError *error = nil;
                [[NSFileManager defaultManager] createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:&error];
                if (error) {
                    NSLog(@"Picutures文件夹创建失败");
                }else{
                    //            [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:pictureBasePath]];
                    NSLog(@"Picutures文件夹创建成功");
                }
            }
            
            NSString *pictureName = [NSString stringWithFormat:@"%.4ld.png",_imgIdx];
            NSString *picturePath = [NSString pathWithComponents:[NSArray arrayWithObjects:tempPath, pictureName, nil]];
//            NSLog(@"=====%@",[UIImage imageWithContentsOfFile:obj]);
            [UIImageJPEGRepresentation(image, 1.0) writeToFile:picturePath atomically:YES];
            _imagePath = tempPath;
            
            _imgIdx += 1;
            CFRelease(sbuff);
        }else{
            // Finish reading
            NSLog(@"_imagesArr====%ld",(unsigned long)videoImageArr.count);
            
        }
    }
    return videoImageArr;
}
-(UIImage *)getVideoShotImage{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(DEVICE_SIZE.width, DEVICE_SIZE.height), YES, 0);     //设置截屏大小
    UIView *view = [[[[[UIApplication sharedApplication] windows] objectAtIndex:1] subviews] lastObject];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    //    CGRect rect = CGRectMake(166, 211, 426, 320);//这里可以设置想要截图的区域
    CGRect rect = CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.width);//这里可以设置想要截图的区域
    CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *ShotImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    return ShotImage;
}

- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    // Get a CMSampleBuffer's Core Video image buffer for the media data
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer, 0);
    
    // Get the number of bytes per row for the pixel buffer
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    
    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    // Create a device-dependent RGB color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // Create a bitmap graphics context with the sample buffer data
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault);
    // Create a Quartz image from the pixel data in the bitmap graphics context
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    // Unlock the pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    
    
    // Free up the context and color space
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    // Create an image object from the Quartz image
    UIImage *image = [UIImage imageWithCGImage:quartzImage];
    
    // Release the Quartz image
    CGImageRelease(quartzImage);
    
    return (image);
}

#pragma mark - Touch Event
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_isProcessingData) {
        return;
    }
    
    if (_deleteButton.style == DeleteButtonStyleDelete) {//取消删除
        [_deleteButton setButtonStyle:DeleteButtonStyleNormal];
        [_progressBar setLastProgressToStyle:ProgressBarProgressStyleNormal];
        return;
    }
    
    UITouch *touch = [touches anyObject];
    
    CGPoint touchPoint = [touch locationInView:_recordButton.superview];
    if (CGRectContainsPoint(_recordButton.frame, touchPoint)) {
//        [self.circularProgressView play];
//        self.circularProgressView.playOrPauseButtonIsPlaying = YES;
//        NSString *filePath = [SBCaptureToolKit getVideoSaveFilePathStringWithVideoTag:_videoTag];
//        [_recorder startRecordingToOutputFileURL:[NSURL fileURLWithPath:filePath]];
    }
    
    touchPoint = [touch locationInView:self.view];//previewLayer 的 superLayer所在的view
    if (CGRectContainsPoint(_recorder.preViewLayer.frame, touchPoint)) {
        [self showFocusRectAtPoint:touchPoint];
        [_recorder focusInPoint:touchPoint];
    }
}

//- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
//    NSLog(@"move");
//    [_circularProgressView pause];
//}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_isProcessingData) {
        return;
    }
    
//    [_recorder stopCurrentVideoRecording];
//    
//    [_circularProgressView pause];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case TAG_ALERTVIEW_CLOSE_CONTROLLER:
        {
            switch (buttonIndex) {
                case 0:
                {
                }
                    break;
                case 1:
                {
                    [self dropTheVideo];
                }
                default:
                    break;
            }
        }
            break;
            
        default:
            break;
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    AVAudioSessionRouteChangeNotification
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
}

#pragma mark ---------rotate(only when this controller is presented, the code below effect)-------------
////<iOS6
//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
//}
//
//
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
////iOS6+
//- (BOOL)shouldAutorotate
//{
//    return NO;
//}
//
//- (NSUInteger)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
//{
//	return UIInterfaceOrientationPortrait;
//}
//#endif


@end
